// pages/order/create.js
const App = getApp()
const CryptoJS = require('crypto-js')
import Kits from '../../utils/kits'
import Util from '../../utils/util'

Page({
    data: {
        init: false,
        back: true,

        car: {},
        user: {},
        timeok: 'check',
        begin: {
            value: undefined,
            year: '',
            date: '',
            time: '',
        },
        close: {
            value: undefined,
            year: '',
            date: '',
            time: '',
        },
        hdays: '',

        method: 1,
        clk: '',

        self: true,
        pickerSelect: false,
        picker: {},
        pickers: [],
        pindex: undefined,

        depotype: 1,

        memo: '',

        dayp: 0,
        bamt: 0,

        svc_onsite: false,
        svc_remote: false,
        svc_bins: false,
        svc_dins: false,
        svc_tins: false,
        svc_free: false,

        onsite_area: '',
        onsite_addr: '',
        onsite_locs: '',

        invoice: {},

        prices: {},
        price: {},

        feeDetails: [],
        feeDetail: false,

        certAlert: false,
        loginAlert: false,
    },

    onLoad(options) {

        console.log('options', options);
        if (options.back != '') {
            this.setData({
                back: options.back != 'false'
            })
        }
        if (options.tag) {
            // 自定义订单、委托下单
            if (!App.Global.User.id) {
                wx.navigateTo({
                    url: '/pages/user/login?next=back',
                    events: {
                        login: () => {
                            this.execLoadTag(options.tag)
                        }
                    }
                })
                return
            } else {
                this.execLoadTag(options.tag)
            }
        } else {

            if (options.clk) {
                // 店员分享车辆
                this.setData({
                    clk: options.clk
                })
            }

            this.doSetDates(new Date(parseInt(options.begin)), new Date(parseInt(options.close)))
            this.setData({
                svc_onsite: options.onsite == 'true',
                onsite_area: options.onsite_area,
                onsite_locs: options.onsite_locs,
                onsite_addr: options.onsite_addr,
            })
            this.execLoad(options.carid)
        }

        this.execLoadUser()
        this.execLoadPicker()

        wx.sub('ReloadUserInfo', this, () => {
            this.execLoadUser()
            this.execLoadPicker()
        })
        wx.sub('ReloadPickerInfo', this, () => {
            this.execLoadPicker()
        })


    },
    onUnload() {
        wx.cancel('ReloadUserInfo', this)
        wx.cancel('ReloadPickerInfo', this)
    },
    execLoadTag(tag) {
        App.doPost({
            uri: '/app/order/create/share/info',
            body: {
                tag: tag,
            },
            fnSucc: resp => {
                this.doSetDates(Kits.parseDatetime(resp.data.begin), Kits.parseDatetime(resp.data.close))

                this.setData({
                    clk: resp.data.clk,
                    method: resp.data.method,
                    dayp: resp.data.method == 3 ? resp.data.custom.day / 100 : resp.data.entrust.day / 100,
                    svc_onsite: resp.data.onsite.flag,
                    svc_remote: resp.data.remote.flag,
                    onsite_area: resp.data.onsite.area,
                    onsite_locs: resp.data.onsite.locs,
                    onsite_addr: resp.data.onsite.addr,
                })
                this.execLoad(resp.data.id)
            },
            fnFail: resp => {
                Util.Notify.error(`[${resp.stat.err}] ${resp.stat.msg}`)
            }
        })
    },
    execLoad(carid) {
        App.doPost({
            uri: '/app/base/biz/car/detail',
            body: {
                id: carid,
                clk: this.data.clk
            },
            fnSucc: resp => {

                resp.data.price.pdpStr = Kits.fmtMoneyString(resp.data.price.pdp)
                resp.data.price.pmpStr = Kits.fmtMoneyString(resp.data.price.pmp)
                resp.data.price.mdpStr = Kits.fmtMoneyString(resp.data.price.mdp)
                resp.data.price.depositStr = Kits.fmtMoneyString(resp.data.price.deposit)
                resp.data.price.dispStr = Kits.fmtMoneyString(resp.data.price.disp)


                resp.data.service.onsite.memo = `${Kits.fmtKilometreString(resp.data.service.onsite.meter)}公里内${Kits.fmtMoneyString(resp.data.service.onsite.cost)}元，超出后每公里${Kits.fmtMoneyString(resp.data.service.onsite.mile)}元`
                resp.data.service.remote.memo = `${Kits.fmtKilometreString(resp.data.service.remote.meter)}公里内${Kits.fmtMoneyString(resp.data.service.remote.cost)}元，超出后每公里${Kits.fmtMoneyString(resp.data.service.remote.mile)}元`
                resp.data.service.bins.memo = `每天${Kits.fmtMoneyString(resp.data.service.bins.cost)}元，封顶${Kits.fmtMoneyString(resp.data.service.bins.max)}元`
                resp.data.service.dins.memo = `每天${Kits.fmtMoneyString(resp.data.service.dins.cost)}元，封顶${Kits.fmtMoneyString(resp.data.service.dins.max)}元`
                resp.data.service.tins.memo = `${resp.data.service.tins.quota}万元三者保额，15天收取${Kits.fmtMoneyString(resp.data.service.tins.cost)}元`
                resp.data.service.free.memo = `${Kits.fmtMoneyString(resp.data.service.free.quota)}元以内，7天收取${Kits.fmtMoneyString(resp.data.service.free.cost)}元`
                resp.data.service.night.memo = `22点-次日7点，每次收费${Kits.fmtMoneyString(resp.data.service.night.cost)}元`
                this.setData({
                    car: resp.data,
                    init: true
                })
                this.execCheckTime()
                this.execCalcPrice()
            },
            fnFail: resp => {
                Util.Notify.error(`[${resp.stat.err}] ${resp.stat.msg}`)
            },
            fnComp: () => {
                this.setData({
                    loading: false
                })
            }
        })
    },
    // 加载用户信息
    execLoadUser() {
        this.setData({
            user: {}
        })
        if (!App.Global.User.id) {
            return
        }
        App.doPost({
            uri: '/app/user/info/profile/info',
            body: {},
            fnSucc: resp => {
                this.setData({
                    user: resp.data
                })
            }
        })
    },
    // 加载取车人
    execLoadPicker() {
        this.setData({
            pickers: [],
            picker: {}
        })
        if (!App.Global.User.id) {
            return
        }
        App.doPost({
            uri: '/app/user/picker/list',
            body: {},
            fnSucc: resp => {
                this.setData({
                    pickers: resp.data.items
                })
            },
        })
    },
    // 检查租赁时间是否可用
    execCheckTime() {
        if (!this.data.car.id) {
            return
        }
        this.setData({
            timeok: 'check'
        })
        App.doPost({
            uri: '/app/base/biz/car/state',
            body: {
                id: this.data.car.id,
                begin: new Date(this.data.begin.value).format('yyyy-MM-dd HH:mm:ss'),
                close: new Date(this.data.close.value).format('yyyy-MM-dd HH:mm:ss')
            },
            fnSucc: resp => {
                this.setData({
                    timeok: resp.data.flag ? 'true' : 'false'
                })
            }
        })
    },
    // 计算价格
    execCalcPrice() {
        if (!this.data.init) {
            return
        }
        this.setData({
            price: {}
        })
        if (this.data.method != 1 && this.data.dayp == 0) {
            return
        }
        if (this.data.method != 1) {
            let bamt = this.data.dayp - parseFloat(this.data.car.price.pdpStr)
            if (bamt <= 0) {
                return
            }
            this.setData({
                bamt: bamt
            })
        }
        if ((this.data.svc_onsite || this.data.svc_remote) && this.data.onsite_locs == '') {
            return
        }
        let body = {
            cid: this.data.car.id,
            mem: false,
            uid: App.Global.User.id,
            begin: new Date(this.data.begin.value).format('yyyy-MM-dd HH:mm:ss'),
            close: new Date(this.data.close.value).format('yyyy-MM-dd HH:mm:ss'),
            method: this.data.method,
            mine: {},
            entrust: {
                day: parseInt(parseFloat(this.data.dayp) * 100),
            },
            custom: {
                day: parseInt(parseFloat(this.data.dayp) * 100)
            },
            onsite: {
                flag: this.data.svc_onsite,
                area: this.data.onsite_area,
                addr: this.data.onsite_addr,
                locs: this.data.onsite_locs
            },
            remote: {
                flag: this.data.svc_remote,
                area: this.data.onsite_area,
                addr: this.data.onsite_addr,
                locs: this.data.onsite_locs
            },
            service: {
                bins: this.data.svc_bins,
                dins: this.data.svc_dins,
                tins: this.data.svc_tins,
                free: this.data.svc_free
            },
            deposit: this.data.depotype
        }

        let md5 = CryptoJS.MD5(JSON.stringify(body)).toString()
        if (this.data.prices[md5] != undefined) {
            this.setData({
                price: this.data.prices[md5],
                feeDetails: this.data.prices[md5].fees,
            })
            return
        }
        App.doPost({
            uri: '/app/base/order/create/price/calc',
            body: body,
            fnSucc: resp => {
                resp.data.totalStr = Kits.fmtMoneyString(resp.data.total)
                resp.data.brokerageStr = Kits.fmtMoneyString(resp.data.bamt)
                this.data.prices[md5] = resp.data
                this.setData({
                    price: resp.data,
                    feeDetails: resp.data.fees,
                })
            },
            fnFail: resp => {
                Util.Notify.error(`[${resp.stat.err}] ${resp.stat.msg}`)
            },
            fnComp: () => {
                this.setData({
                    loading: false
                })
            }
        })
    },
    // 创建订单
    execCreate() {
        if (!this.data.init) {
            return
        }
        if (!App.Global.User.id) {
            this.setData({
                loginAlert: true,
            })
            return
        }
        if (this.data.user.idc.state == 0 || this.data.self && this.data.user.dlc.state == 0) {
            this.setData({
                certAlert: true,
            })
            return
        }

        if (this.data.timeok != 'true') {
            Util.Toast.fail('该时间无法出租')
            return
        }
        if ((this.data.svc_onsite || this.data.svc_remote) && this.data.onsite_locs == '') {
            Util.Toast.fail('请选择送车位置')
            return
        }
        if (this.data.self) {
            if (this.data.user.idc.state == 0 || this.data.user.dlc.state == 0) {
                Util.Toast.fail('请在个人信息认证后下单')
                return
            }
        } else {
            if (this.data.user.idc.state == 0) {
                Util.Toast.fail('请在个人信息认证后下单')
                return
            }
            if (!this.data.picker.id) {
                Util.Toast.fail('请选择取车人')
                return
            }
        }

        let body = {
            id: this.data.car.id,
            begin: new Date(this.data.begin.value).format('yyyy-MM-dd HH:mm:ss'),
            close: new Date(this.data.close.value).format('yyyy-MM-dd HH:mm:ss'),
            method: this.data.method,
            clk: this.data.clk,
            mine: {
                dlc: this.data.self ? this.data.user.dlc.id : this.data.picker.id,
            },
            entrust: {
                day: parseInt(parseFloat(this.data.dayp) * 100),
            },
            custom: {
                day: parseInt(parseFloat(this.data.dayp) * 100)
            },
            onsite: {
                flag: this.data.svc_onsite,
                area: this.data.onsite_area,
                addr: this.data.onsite_addr,
                locs: this.data.onsite_locs
            },
            remote: {
                flag: this.data.svc_remote,
                area: this.data.onsite_area,
                addr: this.data.onsite_addr,
                locs: this.data.onsite_locs
            },
            service: {
                bins: this.data.svc_bins,
                dins: this.data.svc_dins,
                tins: this.data.svc_tins,
                free: this.data.svc_free
            },
            deposit: this.data.depotype,
            memo: this.data.memo,
            invoice: this.data.invoice,
        }

        App.doPost({
            uri: '/app/order/create/submit',
            body: body,
            fnSucc: resp => {
                let info = {
                    id: resp.data.id,
                    expire: resp.data.expire,
                    total: resp.data.total
                }
                wx.redirectTo({
                    url: `/pages/order/pay?src=create&biz=Rent&info=${ JSON.stringify(info) }`,
                })
            },
            fnFail: resp => {
                Util.Notify.error(`[${resp.stat.err}] ${resp.stat.msg}`)
            },
            fnComp: () => {
                this.setData({
                    loading: false
                })
            }
        })
    },
    // 选择地点
    doSelectLocs(e) {
        if (this.data.method == 3 && (this.data.svc_onsite || this.data.svc_remote)) {
            return
        }
        let lng = this.data.onsite_locs ? parseFloat(this.data.onsite_locs.split(',')[0]) : undefined
        let lat = this.data.onsite_locs ? parseFloat(this.data.onsite_locs.split(',')[1]) : undefined
        wx.chooseLocation({
            longitude: lng,
            latitude: lat,
            success: (res) => {

                let locs = res.longitude.toFixed(6) + ',' + res.latitude.toFixed(6)
                App.doPost({
                    uri: '/comm/tool/locs/info',
                    body: {
                        locs: locs
                    },
                    fnSucc: resp => {
                        if (e.currentTarget.dataset.type == 'onsite') {
                            this.setData({
                                onsite_addr: res.name,
                                onsite_area: resp.data.area.code + "",
                                onsite_locs: locs
                            })
                        } else {
                            this.setData({
                                onsite_addr: res.name,
                                onsite_area: resp.data.area.code + "",
                                onsite_locs: locs,
                                remote_addr: res.name,
                                remote_area: resp.data.area.code + "",
                                remote_locs: locs
                            })
                        }
                        this.execCalcPrice()
                    },
                    fnFail: () => {
                        Util.Toast.fail('未知地点信息')
                    }
                })
            },
            fail: (err) => {
                console.log(err)
            }
        })
    },
    // 设置日期
    doSetDates(beginTime, closeTime) {
        let begin = {
            value: beginTime.getTime(),
            year: beginTime.format('yyyy'),
            date: beginTime.format('MM月dd日'),
            time: beginTime.format('HH:mm'),
        }
        let close = {
            value: closeTime.getTime(),
            year: closeTime.format('yyyy'),
            date: closeTime.format('MM月dd日'),
            time: closeTime.format('HH:mm'),
        }
        this.setData({
            begin: begin,
            close: close,
            hdays: Kits.getDateMemo(beginTime, closeTime)
        })
        this.execCheckTime()
        this.execCalcPrice()
    },
    doShowFeeDetails() {
        this.setData({
            feeDetail: true
        })
    },
    doHideFeeDetails() {
        this.setData({
            feeDetail: false
        })
    },
    doSelectPicker() {
        this.setData({
            pickerSelect: true
        })
    },
    hideSelectPicker() {
        this.setData({
            pickerSelect: false
        })
    },
    doPickerChange(e) {
        this.setData({
            picker: e.currentTarget.dataset.picker,
            pickerSelect: false
        })
    },
    // 跳转选择日期界面
    toSelectDate() {
        wx.navigateTo({
            url: `/pages/order/calendar?carid=${this.data.car.id}&begin=${this.data.begin.value}&close=${this.data.close.value}`,
            events: {
                enter: (e) => {
                    this.doSetDates(new Date(e.begin), new Date(e.close))
                }
            }
        })
    },
    // 跳转填写发票信息
    toSelectInvoice() {
        wx.navigateTo({
            url: `/pages/order/invoice`,
            events: {
                enter: (e) => {
                    this.setData({
                        invoice: e
                    })
                }
            },
            success: (res) => {
                res.eventChannel.emit('current', this.data.invoice)
            }
        })
    },
    toAddPicker() {
        wx.navigateTo({
            url: '/pages/mine/picker/index',
        })
    },
    toLogin() {
        this.setData({
            loginAlert: false,
        })
        wx.navigateTo({
            url: '/pages/user/login',
        })
    },
    // 转到个人中心
    toUser() {
        wx.navigateTo({
            url: '/pages/mine/info/user',
        })
    },
    // 关闭弹窗
    closeModal() {
        this.setData({
            certAlert: false
        })
    },

    // 更换押金方式
    doDepoTypeChange(e) {
        this.setData({
            depotype: parseInt(e.currentTarget.dataset.type)
        })
    },
})